from django.shortcuts import render
from .models import Addr,OrderGoods,OrderInfo,Payment,User
from rest_framework.views import APIView
from rest_framework.response import Response

# Create your views here.
class Order(APIView):
    def get(self,request):
        data=OrderInfo.objects.all()
        order=[]
        for i in data:
            order.append({
                'order_id':i.order_id,
                'created_time':i.created_time
            })
        return Response(order)

class OrderGood(APIView):
    def get(self,request,id):
        try:
            order=OrderInfo.objects.get(order_id=id)
            user=User.objects.get(id=order.user_id)
            goods=OrderGoods.objects.filter(order_id=id)
            print(goods)
            good_list=[]
            for i in goods:
                good_list.append({
                    'sku':{
                        'name':i.sku.name,
                        'image_default': i.sku.image_default,
                    },
                    'price':i.price,
                    'count': i.count
                })
                print(i.sku.image_default)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'订单获取失败'})
        return Response({
            'order_id':order.order_id,
            'user': user.username,
            'status': order.status,
            'total_count': order.total_count,
            'total_amount': order.total_amount,
            'freight': order.freight,
            'pay_method': order.pay_method,
            'created_time': order.created_time,
            'skus':good_list
        })
    def post(self,request,id):
        status=request.data.get('status')
        try:
            order = OrderInfo.objects.get(order_id=id)
            order.status=status
            order.save()
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'订单状态修改失败'})
        return Response({'code':200,'msg':'订单状态修改成功'})



